package com.mall.order.mq.delay;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @Description: ${DESCRIPTION}
 * @Author: 徐能雄
 * @Date: 2021/10/4 21:52
 */
@Component
public class DelayOrderCancelProducer {

    DefaultMQProducer producer;

    @PostConstruct
    //该注解可实现spring初始化该对象后自动调用该方法
    public void init() {

        // 1. 创建一个RocketMq中定义好的一个Prouder对象
        producer = new DefaultMQProducer("delay_cancel_order_producer");

        //2. 设置nameserver的地址
        producer.setNamesrvAddr("127.0.0.1:9876");

        //3. 启动producer
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public boolean sendDelayCancelOrderMassage(String orderId) {

        //4. 准备好待发送的消息
        Message message = new Message();
        message.setTopic("delay_order_cancel");
        message.setBody(orderId.getBytes(Charset.forName("utf-8")));

        //5. 设置消息延时时间
        // 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m  8m  9m 10m 20m 30m 1h 2h
        // 1  2  3   4   5  6  7  8  9  10 11  12  13 14  15  16  17 18
        message.setDelayTimeLevel(5);

        //根据结果判断发送状态
        SendResult sendResult = null;
        try {
            sendResult = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())){
            return true;
        }
        return false;
    }


}
